﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using IndexMarkSilverlightClient.IndexMarkServiceReference;
using System.Collections.ObjectModel;
using System.Windows.Data;
using System.ComponentModel;
using IndexMarkSilverlightClient.Classes;
using System.Windows.Controls.Primitives;
using VolumPPS = IndexMarkSilverlightClient.IndexMarkServiceReference.VolumsPPS;
using IndexMarkSilverlightClient.Views.Controls.ReportsControls;
using System.Reflection;

namespace IndexMarkSilverlightClient.Views.Controls
{
    public partial class VolumsPPS : UserControl, INotifyPropertyChanged
    {
        IndexMarkServiceClient client = new IndexMarkServiceClient();
        int TermID;
        ObservableCollection<int> Cats = new ObservableCollection<int>();
        ObservableCollection<int> Sections = new ObservableCollection<int>();

        ObservableCollection<VolumPPS> volums = new ObservableCollection<VolumPPS>();

        public PagedCollectionView Volums
        {
            get
            {
                PagedCollectionView Vol = new PagedCollectionView(this.volums);
                Vol.GroupDescriptions.Add(new PropertyGroupDescription("Section"));
                Vol.SortDescriptions.Add(new SortDescription("Section.Order", ListSortDirection.Ascending));

                return Vol;
            }
        }



        private ObservableCollection<Respondent> pps;
        
        public ObservableCollection<Respondent> PPS
        {
            get
            {
                List<Respondent> list = pps.Where(x=>x.IsSelected).OrderBy(x=>x.Person.ToString()).ToList();
                ObservableCollection<Respondent> Teahers = new ObservableCollection<Respondent>();
                foreach (var Teaher in  list)
                {
                    Teahers.Add(Teaher);
                }
                return Teahers;
            }
        }
        
        public VolumsPPS()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            var vm = MainPage.ViewModel;
            vm.SelectTerm -= ViewModel_SelectTerm;
            vm.SelectTerm += new MainViewModel.SelectTermEventHandler(ViewModel_SelectTerm);
            vm.SelectTermInit();

            client.GetVolumsPPSCompleted += new EventHandler<GetVolumsPPSCompletedEventArgs>(client_GetVolumsPPSCompleted);
            loadingBar.Visibility = Visibility.Collapsed;
        }

        void client_GetVolumsPPSCompleted(object sender, GetVolumsPPSCompletedEventArgs e)
        {
            volums.Clear();

            foreach (var vp in e.Result)
            {
                vp.Category.ImagePath = ImageRepository.Instance.SetTreeItemImage(vp.Char);
                volums.Add(vp);

            }

            // this.DataContext = this.PPS;
            VolumsGrid.ItemsSource = Volums;

            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("Volums"));
                PropertyChanged(this, new PropertyChangedEventArgs("PPS"));
            }

            try
            {
                VolumsGrid.Columns[3].Header = pps;
            }
            catch
            {

            }



            loadingBar.Visibility = Visibility.Collapsed;
            VolumsGrid.Visibility = Visibility.Visible;
        }   

        void ViewModel_SelectTerm(object sender, Classes.SelectTermEventsArgs e)
        {
            TermID = e.SelectTerm.IDTerm;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void VolumsGrid_LoadingRowGroup(object sender, DataGridRowGroupHeaderEventArgs e)
        {
            e.RowGroupHeader.PropertyNameVisibility = System.Windows.Visibility.Collapsed;
            e.RowGroupHeader.ItemCountVisibility = System.Windows.Visibility.Collapsed;

            CollectionViewGroup ViewGroup = e.RowGroupHeader.DataContext as CollectionViewGroup;

            if (ViewGroup.Name.ToString()[1] == '1')
            {
                e.RowGroupHeader.Background = new SolidColorBrush(Color.FromArgb(255, 197, 190, 151));
            }
            if (ViewGroup.Name.ToString()[1] == '2')
            {
                e.RowGroupHeader.Background = new SolidColorBrush(Color.FromArgb(255, 141, 180, 227));
            }
            if (ViewGroup.Name.ToString()[1] == '3')
            {
                e.RowGroupHeader.Background = new SolidColorBrush(Color.FromArgb(255, 230, 185, 184));
            }
            if (ViewGroup.Name.ToString()[1] == '4')
            {
                e.RowGroupHeader.Background = new SolidColorBrush(Color.FromArgb(255, 215, 228, 188));
            }
            if (ViewGroup.Name.ToString()[1] == '5')
            {
                e.RowGroupHeader.Background = new SolidColorBrush(Color.FromArgb(255, 204, 192, 218));
            }
            if (ViewGroup.Name.ToString()[1] == '6')
            {
                e.RowGroupHeader.Background = new SolidColorBrush(Color.FromArgb(255, 182, 221, 232));
            }
            if (ViewGroup.Name.ToString()[1] == '7')
            {
                e.RowGroupHeader.Background = new SolidColorBrush(Color.FromArgb(255, 252, 213, 180));
            }
        }

        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            IndexMarkServiceReference.VolumsPPS VPPS = VolumsGrid.SelectedItem as IndexMarkServiceReference.VolumsPPS;
            OrderedVolums OV = new OrderedVolums();
            OV.IDCharGrad = VPPS.IDCharGrad; 
            OV.Characteristic = "Показатель: " + VPPS.Char.Order + VPPS.Char.Name;
            OV.Gradation = "Градация: " + VPPS.Gradations.First();
            OV.Show();
        }

        void IS_Closing(object sender, CancelEventArgs e)
        {
            if ((sender as IndexSettings).DialogResult == true)
            {
                //pps.Clear();
                //foreach (var Teaher in (sender as IndexSettings).USTU.Teahers)  
                //{
                //    pps.Add(Teaher);
                //}

                Cats = (ObservableCollection<int>)(sender as IndexSettings).Categories;
                var Chars = new ObservableCollection<int>();
                var s = (sender as IndexSettings).SelectedSections;
                var c = (sender as IndexSettings).SelectedCategories.ToList();
                var r = (sender as IndexSettings).SelectedRespondents.ToList();
                var ch = (sender as IndexSettings).SelectedCharacteristics.ToList();

                foreach (var Sec in s)
                {
                    Sections.Add(Sec.ID);
                }


                foreach (var cat in c)
                {
                    Cats.Add(cat.IDCategory);
                }

                foreach (var cha in ch)
                {
                    Chars.Add(cha.ID);
                }

                ObservableCollection<int> Resps = new ObservableCollection<int>();
                pps = new ObservableCollection<Respondent>();
                r = r.OrderBy(x=>x.Person.LastName).ToList();
                foreach (var Teaher in r)
                {
                    Resps.Add(Teaher.IDRespondent);
                    pps.Add(Teaher);
                }

                VolumePPS p = new VolumePPS();
                
                if (VolumsGrid.Columns[3].Header==null) VolumsGrid.Columns[3].Header = PPS;
               
                client.GetVolumsPPSAsync(TermID, Resps, Chars, Cats);
                loadingBar.Visibility = Visibility.Visible;
                VolumsGrid.Visibility = Visibility.Collapsed;
            }   
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            IndexSettings IS = new IndexSettings();
            IS.ISTree.HideChars();
            IS.USTU.Check = false;
            IS.SettingsItemVisible = false;
            IS.CurrentTermID = TermID;
            IS.Closing += new EventHandler<CancelEventArgs>(IS_Closing);
            IS.Show();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            exportToExel();

        }

        void exportToExel()
        {
            
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Простой файл электронных таблиц | *.csv";
            if (sfd.ShowDialog().Value)
            {
                using (StreamWriter SW = new StreamWriter(sfd.OpenFile(), CConst.Encoding))
                {
                    if (volums.Count != 0)
                    {
                        SW.Write(";Показатель; Ед.изм.;");
                        int respCol = PPS.Count;
                        foreach (var respondent in PPS)
                        {
                            SW.Write(respondent.Person.ToString()+";;");
                        }
                        SW.WriteLine();

                        foreach (var volum in Volums.Groups)
                        {

                            CollectionViewGroup group = volum as CollectionViewGroup;
                            SW.WriteLine("Раздел " + group.Name);
                            foreach (var item in group.Items)
                            {
                                //пишем харектеристику и ед изм
                                VolumPPS p = item as VolumPPS;
                                //SW.Write(p.Char+";");
                                //SW.Write(p.Char.Unit+ ";");
                                //SW.Write(p.);
                                //пишем АНСВЕРЫ
                                //попробуем сначала сделать таблицу стрингов для записи построчно

                                string[,] table = new string[3 + respCol*2, 100]; //100
                                table[2, 0] = p.Category.Name;
                                table[0, 0] = p.Char.ToString();
                                table[1, 0] = p.Char.Unit;
                                int i = 3; //cтолбцы
                                int maxj = 0;
                                foreach (var col in p.Volums) //бегаем по респондентам
                                {
                                    int j = 0;
                                    foreach (var rowOfAns in col.Answers) // бегаем по ансверам респондента 
                                    {
                                        
                                        table[i + 1, j] =((rowOfAns.Volume.HasValue)
                                                               ? rowOfAns.Volume.Value.ToString()
                                                               : "");
                                        int k = 0; //строки градаций
                                        foreach (var gr in rowOfAns.Gradations) //бегаем по градациям ансвера
                                        {
                                            //пишем значение градации
                                            string str=  (gr.Volume.HasValue) ?( " - " + gr.Volume.Value.ToString()) :"";
                                            table[i, j+k] = gr.Name + str;
                                            k++;
                                        }
                                        j += k;
                                        maxj = (maxj < j) ? j : maxj;
                                    }
                                    i += 2;
                                }

                                for (int z = 0; z < maxj; z+=1)
                                {
                                    for (int w = 0; w < respCol*2+2; w++)
                                    {
                                        SW.Write(table[w,z]+";");
                                    }
                                    SW.WriteLine();
                                }

                            }
                        }
                    }



                    SW.Close();
                }
                MessageBox.Show("Сохранено");
            }
        }



        private void ChildTable_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void TextBlock_Loaded(object sender, RoutedEventArgs e)
        {

        }

    }
}
